Page({
  data: {
    termList: [],
    termIndex: 0,
    classList: [{ id: 0, name: '全部班级' }],
    classIndex: 0,
    courseList: [{ id: 0, name: '全部课程' }],
    courseIndex: 0,
    
    // 统计数据
    statistics: {
      total: 0,
      avgScore: 0,
      passRate: 0,
      excellentRate: 0,
      failRate: 0
    },
    
    // 成绩分布数据
    scoreDistribution: [
      { range: '90-100', count: 0, percentage: 0 },
      { range: '80-89', count: 0, percentage: 0 },
      { range: '70-79', count: 0, percentage: 0 },
      { range: '60-69', count: 0, percentage: 0 },
      { range: '0-59', count: 0, percentage: 0 }
    ],
    
    // 图表配置
    pieChartOption: {},
    barChartOption: {},
    
    // 是否显示图表
    showCharts: false
  },

  onLoad: function(options) {
    // 获取班级列表
    this.fetchClassList();
    
    // 获取课程列表
    this.fetchCourseList();
    
    // 获取学期列表
    this.fetchTermList();
  },
  
  onReady: function() {
    // 页面渲染完成后，初始化图表
    this.initCharts();
  },
  
  // 获取班级列表
  fetchClassList: function() {
    wx.request({
      url: 'http://localhost:3000/api/admin/classes',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const classes = [{ id: 0, name: '全部班级' }, ...res.data];
          this.setData({
            classList: classes
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取班级列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取课程列表
  fetchCourseList: function() {
    wx.request({
      url: 'http://localhost:3000/api/admin/courses',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const courses = [{ id: 0, name: '全部课程' }, ...res.data];
          this.setData({
            courseList: courses
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取学期列表
  fetchTermList: function() {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.showLoading({
      title: '加载学期数据...',
    });
    
    wx.request({
      url: `${serverUrl}/api/admin/timetable/semesters`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          const semestersData = res.data || [];
          
          if (semestersData.length > 0) {
            const termList = semestersData.map(semester => semester.name || semester.id);
            
            this.setData({
              termList: termList,
              termIndex: 0
            }, () => {
              // 获取成绩分析数据
              this.fetchAnalysisData();
            });
          } else {
            // 设置默认值
            this.setData({
              termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
            }, () => {
              this.fetchAnalysisData();
            });
          }
        } else {
          // 设置默认值
          this.setData({
            termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
          });
          this.fetchAnalysisData();
        }
      },
      fail: (err) => {
        wx.hideLoading();
        // 如果请求失败，设置默认值
        this.setData({
          termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
        });
        // 使用默认学期获取成绩数据
        this.fetchAnalysisData();
      }
    });
  },
  
  // 获取成绩分析数据
  fetchAnalysisData: function() {
    wx.showLoading({
      title: '加载分析数据...',
    });
    
    const classId = this.data.classList[this.data.classIndex].id;
    const courseId = this.data.courseList[this.data.courseIndex].id;
    const term = this.data.termList[this.data.termIndex];
    
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/admin/grades/analysis`,
      method: 'GET',
      data: {
        classId: classId === 0 ? '' : classId,
        courseId: courseId === 0 ? '' : courseId,
        term: term
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          // 处理统计数据
          const stats = res.data.statistics || {
            total: 0,
            avgScore: 0,
            passRate: 0,
            excellentRate: 0,
            failRate: 0
          };
          
          // 处理分布数据
          const distribution = res.data.distribution || [];
          
          // 格式化分布数据
          const formattedDistribution = [
            { range: '90-100', count: 0, percentage: 0 },
            { range: '80-89', count: 0, percentage: 0 },
            { range: '70-79', count: 0, percentage: 0 },
            { range: '60-69', count: 0, percentage: 0 },
            { range: '0-59', count: 0, percentage: 0 }
          ];
          
          // 填充分布数据
          distribution.forEach(item => {
            if (item.min >= 90 && item.max <= 100) {
              formattedDistribution[0].count = item.count;
              formattedDistribution[0].percentage = item.percentage;
            } else if (item.min >= 80 && item.max < 90) {
              formattedDistribution[1].count = item.count;
              formattedDistribution[1].percentage = item.percentage;
            } else if (item.min >= 70 && item.max < 80) {
              formattedDistribution[2].count = item.count;
              formattedDistribution[2].percentage = item.percentage;
            } else if (item.min >= 60 && item.max < 70) {
              formattedDistribution[3].count = item.count;
              formattedDistribution[3].percentage = item.percentage;
            } else if (item.min >= 0 && item.max < 60) {
              formattedDistribution[4].count = item.count;
              formattedDistribution[4].percentage = item.percentage;
            }
          });
          
          // 更新数据
          this.setData({
            statistics: stats,
            scoreDistribution: formattedDistribution,
            showCharts: true
          }, () => {
            // 更新图表
            this.updateCharts();
          });
        } else {
          // 请求成功但状态码不是200
          wx.showToast({
            title: '获取分析数据失败',
            icon: 'none'
          });
          
          // 重置为空数据
          this.setData({
            statistics: {
              total: 0,
              avgScore: 0,
              passRate: 0,
              excellentRate: 0,
              failRate: 0
            },
            scoreDistribution: [
              { range: '90-100', count: 0, percentage: 0 },
              { range: '80-89', count: 0, percentage: 0 },
              { range: '70-79', count: 0, percentage: 0 },
              { range: '60-69', count: 0, percentage: 0 },
              { range: '0-59', count: 0, percentage: 0 }
            ],
            showCharts: false
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取分析数据失败:', err);
        wx.showToast({
          title: '获取分析数据失败',
          icon: 'none'
        });
        
        // 重置为空数据
        this.setData({
          statistics: {
            total: 0,
            avgScore: 0,
            passRate: 0,
            excellentRate: 0,
            failRate: 0
          },
          scoreDistribution: [
            { range: '90-100', count: 0, percentage: 0 },
            { range: '80-89', count: 0, percentage: 0 },
            { range: '70-79', count: 0, percentage: 0 },
            { range: '60-69', count: 0, percentage: 0 },
            { range: '0-59', count: 0, percentage: 0 }
          ],
          showCharts: false
        });
      }
    });
  },
  
  // 初始化图表
  initCharts: function() {
    // 初始化饼图
    this.pieChart = this.selectComponent('#pieChart');
    
    // 初始化柱状图
    this.barChart = this.selectComponent('#barChart');
    
    // 更新图表数据
    this.updateCharts();
  },
  
  // 更新图表数据
  updateCharts: function() {
    // 准备饼图数据
    const pieData = {
      series: [{
        data: this.data.scoreDistribution.map(item => ({
          name: item.range,
          value: item.count
        }))
      }]
    };
    
    // 准备柱状图数据
    const barData = {
      categories: this.data.scoreDistribution.map(item => item.range),
      series: [{
        name: '人数',
        data: this.data.scoreDistribution.map(item => item.count)
      }]
    };
    
    this.setData({
      pieChartData: pieData,
      barChartData: barData
    });
  },
  
  // 学期变更
  termChange: function(e) {
    this.setData({
      termIndex: e.detail.value
    });
    
    this.fetchAnalysisData();
  },

  // 班级变更
  classChange: function(e) {
    this.setData({
      classIndex: e.detail.value
    });
  },

  // 课程变更
  courseChange: function(e) {
    this.setData({
      courseIndex: e.detail.value
    });
  },
  
  // 筛选分析数据
  filterAnalysis: function() {
    this.fetchAnalysisData();
  },
  
  // 重置筛选
  resetFilter: function() {
    this.setData({
      classIndex: 0,
      courseIndex: 0
    });
    
    this.fetchAnalysisData();
  },
  
  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
})